package com.code.invoker.base;

import com.code.db.ConnectionUtil;
import com.code.db.TableInformation;
import com.code.task.base.AbstractTask;
import com.code.utils.ConfigUtil;
import com.code.utils.TaskQueue;
import freemarker.template.TemplateException;

import java.io.IOException;
import java.util.List;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public abstract class SingleAbstractInvoker implements Invoker {
    protected TableInformation tableInformation = new TableInformation();
    protected ConnectionUtil connectionUtil = new ConnectionUtil();
    protected TaskQueue taskQueue = new TaskQueue();
    private ExecutorService executorPool = Executors.newFixedThreadPool(6);

    private void initDataSource() throws Exception {
        if (!this.connectionUtil.initConnection()) {
            throw new Exception("Failed to connect to database at url:" + ConfigUtil.getConfiguration().getDb().getUrl());
        }
        initTableInformation();
        connectionUtil.close();
    }

    protected abstract void initTasks();

    protected abstract void initTableInformation();

    @Override
    public void execute() {
        try {
            initDataSource();
            initTasks();
            while (!taskQueue.isEmpty()) {
                AbstractTask task = taskQueue.poll();
                executorPool.execute(() -> {
                    try {
                        task.run();
                    } catch (IOException e) {
                        e.printStackTrace();
                    } catch (TemplateException e) {
                        e.printStackTrace();
                    }
                });
            }
            executorPool.shutdown();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public void setTableName(String tableName) {
        this.tableInformation.setTableName(tableName);
    }

    public void setClassName(String className) {
        this.tableInformation.setClassName(className);
        this.tableInformation.setBaseClassName(className.replace("Entity", ""));
    }

    public void setUnits(List<String> units) {
        this.tableInformation.setUnits(units);
    }
}
